package com.duolia.update;

import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;

import com.duolia.bless.utils.L;
import com.duolia.bless.utils.ResourceUtils;
import com.duolia.download.DownloadTask;

public class DefaultUpdateListener extends AbstractUpdateListener {

	private NotificationManager notificationManager = null;
	private NotificationCompat.Builder notificationBuilder = null;
	private AlertDialog alertDialog = null;
	
	@Override
	public void onStart() {
		Context context = getContext();
        if (context != null) {
        	CharSequence checking;
        	try {
				checking = context.getText(ResourceUtils.getStringId(context, "autoupdate_checking"));
			} catch (Exception e) {
				checking = "autoupdate_checking";
			}
            alertDialog = new AlertDialog.Builder(context)
                    .setMessage(checking)
                    .setCancelable(false)
                    .create();
            alertDialog.show();
        }
	}
	
	@Override
	public void onFinish() {
		if (alertDialog != null) {
            alertDialog.dismiss();
        }
	}
	
	@Override
	public void onShowUpdateUI(final UpdateInfo info) {
		if (info == null) {
            return;
        }
		
		Context context = getContext();
		if (context != null) {
			CharSequence autoupdate_update_tips;
			CharSequence autoupdate_confirm;
			CharSequence autoupdate_cancel;
			CharSequence autoupdate_skip;
			
			try {
				autoupdate_update_tips = context.getResources().getString(ResourceUtils.getStringId(context, "autoupdate_update_tips"));
			} catch (Exception e) {
				autoupdate_update_tips = "update tips";
			}
			
			try {
				autoupdate_confirm = context.getResources().getString(ResourceUtils.getStringId(context, "autoupdate_confirm"));
			} catch (Exception e) {
				autoupdate_confirm = "confirm";
			}
			
			try {
				autoupdate_cancel = context.getResources().getString(ResourceUtils.getStringId(context, "autoupdate_cancel"));
			} catch (Exception e) {
				autoupdate_cancel = "cancel";
			}
			
			try {
				autoupdate_skip = context.getResources().getString(ResourceUtils.getStringId(context, "autoupdate_skip"));
			} catch (Exception e) {
				autoupdate_skip = "skip";
			}
			
            AlertDialog dialog = new AlertDialog.Builder(context)
                    .setTitle(autoupdate_update_tips)
                    .setMessage(getUpdateTips(info))
                    .setPositiveButton(autoupdate_confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            informUpdate(info);
                        }
                    })
                    .setNegativeButton(autoupdate_cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            informCancel(info);
                        }
                    })
                    .setNeutralButton(autoupdate_skip, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            informSkip(info);
                        }
                    })
                    .setCancelable(false)
                    .create();
            dialog.show();
        }
	}
	
	@Override
	public void onShowNoUpdateUI() {
		Context context = getContext();
        if (context != null) {
        	CharSequence autoupdate_no_update;
        	try {
        		autoupdate_no_update = context.getResources().getString(ResourceUtils.getStringId(context, "autoupdate_no_update"));
			} catch (Exception e) {
				autoupdate_no_update = "no update info";
			}
            AlertDialog dialog = new AlertDialog.Builder(context)
                    .setMessage(autoupdate_no_update)
                    .setCancelable(true)
                    .create();
            dialog.show();
        }
	}
	
	@Override
	public void onShowUpdateProgressUI(UpdateInfo info, DownloadTask task, int progress) {
		Context context = getContext();
        if (context != null && task != null && info != null) {
            try {
//                Bitmap largeIcon = null;
                PackageManager pm = context.getPackageManager();
                Drawable icon = pm.getApplicationIcon(context.getPackageName());
//                if (icon != null){
//                    largeIcon =((BitmapDrawable) icon).getBitmap();
//                }

                PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
                String contentTitle = info.getAppName();
                String contentText = new StringBuffer().append(progress).append("%").toString();
                int smallIcon = context.getApplicationInfo().icon;
                if (notificationManager == null) {
                    notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                }

                if (notificationBuilder == null) {
                    notificationBuilder = new NotificationCompat.Builder(context)
                            // .setLargeIcon(largeIcon)
                            .setSmallIcon(smallIcon)
                            .setContentTitle(contentTitle)
                            .setContentText(contentText)
                            .setContentIntent(contentIntent)
                            .setAutoCancel(true);
                }
				if (progress == 100)
				{
					Intent i = new Intent(Intent.ACTION_VIEW);
					i.setDataAndType(Uri.parse("file://" + task.getPath()), "application/vnd.android.package-archive");
					i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					contentIntent = PendingIntent.getActivity(context, 0, i, 0);
					notificationBuilder.setContentIntent(contentIntent);
					notificationBuilder.setContentText("下载完成,点击安装");
				} else {
					notificationBuilder.setContentText(contentText);
	                notificationBuilder.setProgress(100, progress, false);
				}
                notificationManager.notify(0, notificationBuilder.build());
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
                L.e("can not get the package info", e.getLocalizedMessage());
            }
        }
	}
	
	@Override
	public void ExitApp() {
		Context context = getContext();
        if (context != null) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
	}
}
